# this is as the PYTHONSTARTUP target file

async def __main__(argc,argv):
    while use.lives:
        print('atic-atac')
        await aio.sleep(10)


import uio as io
import sys


try:
    use.srv = open('srv','r').read().strip()
    use.host = open('machine','r').read().strip()
except OSError:
    print('machine','config','not','set')

import aio


def sha256(data):
    import hashlib as uhashlib
    import ubinascii
    h = uhashlib.sha256()
    if isinstance(data,str):
        h.update(data.encode('utf-8'))
    else:
        h.update(data)
    return ubinascii.hexlify(h.digest()).decode()


def mkdir(p):
    p = p.rstrip("/\n\r\t")
    try:
        if __UPY__:
            __import__("uos").mkdir(p)
        else:
            __import__("os").mkdir(p)
        return p
    except OSError as e:
        if e.args[0] == 17:
            return

mkdir('cache')


def fopen(f, no_html=False):
    if f.startswith(':'):
        f = f[1:].strip('/')
        u= '{0}/{1}'.format( use.srv, f )
        f = 'cache/%s' % sha256(u)
        try:
            try:
                data = urequests.get(u)
            except:
               print(u)
               raise

            data = data.content
            if no_html and data[0]!=60:
                try:
                    sum = open(f+".sum",'r').read()
                except:
                    sum = ""
                if sha256( data ) != sum:
                    with open(f,'wb') as u:
                        u.write(data)

                    with open(f+".sum",'wb') as u:
                        u.write(sum)
                else:
                    print("fopen",f,"sum","ok")
            else:
                print("fopen",f,"for", u)
        except Exception as e:
            sys.print_exception(e,sys.stderr)
            print('uses',f)
    return open(f,'rb')


builtins.fopen = fopen

if hasattr(use,'host'):
    try:
        code = fopen(':%s.py' % use.host, no_html=True).read().decode()
    except Exception as e:
        code = '#' + repr(e)
        print(code)

    try:
        exec( compile( code , '<%s>' % use.host, 'exec') , globals(),  globals() )
        code=""
        if aio.paused is unset:
            print("start","aio","run_forever")
            aio.loop.run_forever()
            aio.loop.close()

    except Exception as e:
        print("="*79)
        print(code)
        print("="*79)
        sys.print_exception(e,sys.stderr)





_ESC = '\x1b'
_CSI = '\x1b['

def CSI(n,X='',file=sys.stdout):
    global _ESC, _CSI
    file.write( ''.join( [_CSI, n, X] ) )

#import xpy.readline as readline

import xpy.readline as readline

try:
    from xpy.readtouch import ReadTouch
except Exception as e:
    pdb("19: no touch support from xpy.readtouch : {}".format((e)))
    class readtouch:
        def process_touch(self,*a,**k):
            pass


class readline(readline.readline, readtouch):
    old_settings = None
    fd = 0

    MB = {
       'B' : '',
       'C':  0,
        0 : 'L',
        1 : 'M',
        2 : 'R',
        3 : '',
        'D' : { '':'' },
    }

    @classmethod
    def Begin(cls,channel=sys.stdin):
        try:
            import tty
            cls.fd = channel.fileno()
            tty.setraw(cls.fd)
            import termios
            cls.old_settings = termios.tcgetattr(cls.fd)
        except:
            err('no tty or no termios')
        pdb("217: mouse mode 1003")
        CSI('?1003h')

    @classmethod
    def End(cls):
        if cls.old_settings:
            import termios
            if __UPY__:
                termios.tcsetattr(cls.fd, 1, cls.old_settings)
            else:
                termios.tcsetattr(cls.fd, termios.TCSADRAIN, cls.old_settings)

        CSI('?1003l')


readline  = readline()















def repl(prompt=None, password=False):
    __print__ = print

    input = __import__('uio').StringIO()
    input.seek(0)
    tell = 0
    current = prompt
    frames = 0

    if sys.platform in ('esp32',):
        UART=__import__('machine').UART(1, tx=1, rx=3, baudrate=115200)
        __write__ = UART.write

        def switch(input=None):
            if input is not None:
                out(input)
    else:
        UART = __import__('machine').UART(0)
        __write__ = sys.stdout.write

        def switch(input=None):
            if input is not None:
                out(input)
            os.dupterm( None , 1)

    def out(*argv,**kw):

        output = __import__('uio').StringIO()
        if kw.get('file',sys.stdout) in (sys.stdout, sys.stderr,):
            kw['file']=output
            __print__(*argv, **kw)
            output.seek(0)
            data = output.read().encode().replace(b'\n',b'\r\n')
            __write__(data)
            output.close()
        else:
            __print__(*argv, **kw)

    builtins.print = out

    switch(current or '%c[2J%c[0;0H\n=~> ' % (27,27))

    while use.lives:
        try:
            if UART.any():
                current = UART.read(1)
                chr = ord(current)
                if chr<127:
                    if chr>31:
                        input.seek(tell)
                        input.write(current)
                        tell += 1
                        if current == b'X' :
                            try:
                                UART.deinit()
                            except:
                                pass
                            finally:
                                machine.reset()

                    elif chr in [13,10]: #???? flush 10 ?
                        out('\n')
                        input.seek(0)
                        out( input.read() )
                        out('\n')
                        input = __import__('uio').StringIO()
                        input.seek(0)
                        tell = 0
                        current = prompt
                    else:
                        out('\nCTRL : %s\n' % chr )


                elif chr==127:
                    tell -= 1 if tell>0 else 0

                switch(current)
                current = None

            else:
                Time.sleep(.016)
                frames +=1
                if frames > 25*10:
                    out(b'tic-tac\n')
                    frames=0
        except Exception as e:
            __write__( repr(e).encode() )



#print("\x1b[1,12r",end="")
#print("Scroll reg 1-12");















































#
